var SM = SM || {}
SM.ErrorReports = function(){
    var  btnViewReports = [], chkConfigs = [], paginator, displayDivs=[], rowsPerPage=10, selRowsPerPage, messageOptions, selDomains;

    var merge = function (obj1, obj2){
        if(!YAHOO.lang.isUndefined(obj2.length)){
            for(var i=0; i < obj2.length; i++){
                obj1.push(obj2[i]);
            }
        }
        return obj1;
    }

    var showMessageContainerByConfigId = function(configId){
        for(var i=0; i < chkConfigs.length; i++){
            if(chkConfigs[i].id == configId){
                break;
            }
        }
        var els = YAHOO.util.Dom.getElementsByClassName(chkConfigs[i].className);
        
        if(displayDivs.length == 0 && els.length > 0){
//            YAHOO.log("set displayDivs to els");
            displayDivs = els;
//            YAHOO.log("after initial set displayDivs.length: " + displayDivs.length);
//            YAHOO.log(YAHOO.lang.dump(displayDivs));
        }else if(els.length > 0){
//            YAHOO.log("merge arrays");
            displayDivs = merge(displayDivs, els);
//            YAHOO.log("wtf? " + YAHOO.lang.dump(displayDivs));

//            YAHOO.log("after merge displayDivs.length: " + displayDivs.length);
        }
        
//        YAHOO.log("className: " + chkConfigs[i].className + ", els.length: " + els.length);
//        YAHOO.log("displayDivs.length: " + displayDivs.length);


        //YAHOO.log("displayDivs.length: " + displayDivs.length);
        //addClass(els, "blockDisplay");
    }

    var showMessageContainers = function(){
        for(var i=0; i < btnViewReports.length; i++){
            if(btnViewReports[i].checked){
                showMessageContainerByConfigId(btnViewReports[i].id);
            }
        }

        for(i=0; i < displayDivs.length; i++){
            YAHOO.log("id, " + displayDivs[i].id);
        }
    }

    var addChkConfig = function(config){
        chkConfigs.push(config);
    }

    var setButtonVars = function(configs){
        for(var i=0; i < configs.length; i++){
            var el = YAHOO.util.Dom.get(configs[i].id);
            btnViewReports.push(el);
        }
    }

    var bindEvents = function(els, event, callback, obj){
        if(!obj){
            obj = null;
        }
        YAHOO.util.Event.addListener(els, event, callback, obj);
    }

    var removeClass = function(els, className){
        for(var i=0; i < els.length; i++){
            YAHOO.util.Dom.removeClass(els[i], className);
        }
    }

    var addClass = function(els, className){
        for(var i=0; i < els.length; i++){
            YAHOO.util.Dom.addClass(els[i], className);
        }
    }

    var getMessageClassName = function(el, configs){
        for(var i=0; i < configs.length; i++){
            if(configs[i].id == el.id){
//                YAHOO.log("id: " + el.id + ", className: " + configs[i].className);
                return configs[i].className;
                break;
            }
        }
    }

    var showMessage = function(els, className){
        //addClass(els, "blockDisplay");
        var attributes = {
           opacity: {to: 1},
           margin: {to: 5}
        };
        setMessageAnimation(els, attributes);
    }

    var hideMessage = function(els, className){
        var attributes = {
           margin: {to: 0}
        };

        setMessageAnimation(els, attributes, function(){
            //removeClass(els, "blockDisplay");
        });
    }

    var toggleMessages = function(e, configs){
        YAHOO.log(YAHOO.lang.dump("configs: " + configs));
        var target = YAHOO.util.Event.getTarget(e);
        className = getMessageClassName(target, configs);

        var els = YAHOO.util.Dom.getElementsByClassName(className);

        if(target.checked){
            //showMessage(els, className);
        }else{
            hideMessage(els, className);
        }
        
        initViewport();
    }

    var setMessageAnimation = function(elem, attributes, callback){
        var messageAnim = new YAHOO.util.Anim(elem, attributes);
        messageAnim.duration = 0.5;
        messageAnim.method = YAHOO.util.Easing.easeOut;
        if(YAHOO.lang.isFunction(callback)){
           messageAnim.onComplete.subscribe(callback);
        }

        messageAnim.animate();
    }

    var displayDivsSelectionSort = function(arr) {
       var n = arr.length, min, tmp;
       for(var i = 0; i < arr.length; i++) {
          min = i;
          for(var j = i + 1; j < n; j++){
             if(parseInt(arr[j].id) < parseInt(arr[min].id)){
                min = j;
             }
          }
          tmp = arr[min];
          arr[min] = arr[i];
          arr[i] = tmp;
       }

       return arr;
    }

    var clearDisplayDivs = function(){
        var els = YAHOO.util.Dom.getElementsByClassName("sm_message");
        YAHOO.util.Dom.removeClass(els, "blockDisplay");
    }

    var initViewport = function(){
        // clear sm_message display attribute
        clearDisplayDivs();

        // reset displayDivs array
        displayDivs = [];

        // place displayable divs in displayDivs array
        showMessageContainers();

        paginator.set('totalRecords', displayDivs.length);
        paginator.set('rowsPerPage', rowsPerPage);
        paginator.render();

        var currentPage=paginator.getCurrentPage(), start=rowsPerPage*(currentPage-1);

        // sort displayDivs by id before continuing
        displayDivs = displayDivsSelectionSort(displayDivs);

        YAHOO.log("after show containers: " + YAHOO.lang.dump(displayDivs));
        YAHOO.log("displayDivs length: " + displayDivs.length);
        YAHOO.log("currentPage: " + currentPage);
        YAHOO.log("start: "+ rowsPerPage*(currentPage-1));
        YAHOO.log("rowsPerPage: " + rowsPerPage);

        for(var i=start, j=0; (j < rowsPerPage) && (j < displayDivs.length); i++, j++){
            YAHOO.util.Dom.addClass(displayDivs[i], "blockDisplay");
        }
    }

    var MyApp = {
        handlePagination : function (newState) {
            // Collect page data using the requested page number
            //var pageContent = MyApp.getContent(newState.page);

            // Update the content area
            //MyApp.replaceContent(pageContent);

            // Update the Paginator's state
            paginator.setState(newState);
            initViewport();
        }
    };
 
    var initPaginator = function(){
        paginator = new YAHOO.widget.Paginator({
            rowsPerPage  : rowsPerPage,
            totalRecords : 1, // dummy value needed to initialize paginator object
            containers   : "paginator"
        });
        paginator.subscribe('changeRequest',MyApp.handlePagination);
        //paginator.render();
    }

    var handleRowsPerPage = function(event){
        var target = YAHOO.util.Event.getTarget(event);

        rowsPerPage = target.value;
        initViewport();
    }

    var handleMessageOptions = function(event){
        var target = YAHOO.util.Event.getTarget(event);
        var messageCallback = {
            success: messageResponseSuccess,
            failure: messageResponseFailure
        }

//        alert(target.className);
        if(target.className == "messageDelete"){
            var array = this.id.split("_");
            var postQueryString = "id=" + array[1] + "&action=delete";
            var transaction = YAHOO.util.Connect.asyncRequest('POST', sEditMessage, messageCallback, postQueryString);
        }
    }

    var reportResponseSuccess = function(o){
        try{
            var result = YAHOO.lang.JSON.parse(o.responseText);
            displayReport(result);

            // bind functionality to message containers
            messageOptions = YAHOO.util.Dom.getElementsByClassName("messageOptions");
            YAHOO.util.Event.addListener(messageOptions, "click", handleMessageOptions);
        }catch (e) {
            alert("error: " + e.message + "\nfile: " + e.fileName + "\nln: " + e.lineNumber);
        }
    }

    var reportResponseFailure = function(o){
        alert("failure");
    }

    var reportCallback = {
        success: reportResponseSuccess,
        failure: reportResponseFailure
    }

    var viewReport = function(){
        var domain_name, postQueryString;
        // get selected domain id
        for(var i=0; i < selDomains.length; i++){
            if(selDomains.options[i].selected){
                domain_name = selDomains.options[i].text;
                break;
            }
        }

        postQueryString = "domain_name=" + domain_name + "&page=1&records=10";
        var transaction = YAHOO.util.Connect.asyncRequest('POST', sReport, reportCallback, postQueryString);
    }

    var init = function(){
        setButtonVars(chkConfigs);
        bindEvents(btnViewReports, "click", toggleMessages, chkConfigs); // why did I bind events in this fashion?

        selRowsPerPage = YAHOO.util.Dom.get("selRowsPerPage");
        YAHOO.util.Event.addListener(selRowsPerPage, "change", handleRowsPerPage);

        selDomains = YAHOO.util.Dom.get("selDomains");
        

        initPaginator();
    }

    return {
        init:init,
        addChkConfig:addChkConfig,
        showMessageContainers:showMessageContainers,
        initPaginator:initPaginator,
        initViewport:initViewport
    }
}();

SM.YUILoader.registerCallback(SM.ErrorReports.init);
SM.ControlPanel.registerDisplayReportCallbacks(SM.ErrorReports.initPaginator);
SM.ControlPanel.registerDisplayReportCallbacks(SM.ErrorReports.initViewport);
//SM.ControlPanel.addRowsPerPageCallback(SM.ErrorReports.changeRowsPerPage);
